//
//  FriendVerifyViewController.m
//  SouthChina
//
//  Created by Mr.Y on 15/1/9.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "FriendVerifyViewController.h"
#import "FriendVerifyCell.h"
#import "MessageSessionDao.h"
#import "ContactDao.h"
#import "FriendDetailViewController.h"
#import "JoinGrpValidateViewController.h"


@interface FriendVerifyViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,OnOperateButtonClick>
{
    NSArray *msgList;

}
@property (strong, nonatomic) UITableView * friendVerifyTableView;
@end

@implementation FriendVerifyViewController

@synthesize session;


- (void)viewDidLoad {
    [super viewDidLoad];
    if ([session.sess_id isEqualToString:@"cmd_friendValidate"]) {
        [self addTitleBarWithBackBtn:@"好友验证" needReturn:YES];
    }
    else if ([session.sess_id isEqualToString:@"cmd_sendJoinGrpRequest"])
    {
        [self addTitleBarWithBackBtn:@"入群邀请" needReturn:YES];
    }else if([session.sess_id isEqualToString:@"cmd_applyToJoinGrp"])
    {
         [self addTitleBarWithBackBtn:@"入群申请" needReturn:YES];
    }
    
    _friendVerifyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    
    _friendVerifyTableView.delegate = self;
    _friendVerifyTableView.dataSource = self;
    _friendVerifyTableView.rowHeight = 64;
    _friendVerifyTableView.bounces = NO;
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [_friendVerifyTableView setTableFooterView:view];
    [_friendVerifyTableView setTableHeaderView:view];
    
    [self.view addSubview:_friendVerifyTableView];
    NSLog(@"session.sess_id..........%@",session.sess_id);
    msgList= [MessageDao queryMessageBySessionId:session.sess_id];
    NSLog(@"个数.......%lu",msgList.count);
      // Do any additional setup after loading the view.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return msgList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *message = [msgList objectAtIndex:indexPath.row];
    static NSString * CellIdentifier = @"FriendVerifyCell";
    FriendVerifyCell * cell = (FriendVerifyCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        cell.onPsBtnLinstener = self;
        cell.headImage.layer.masksToBounds = YES;
        cell.headImage.layer.cornerRadius = 8.0;
        UIImage *img=[UIImage imageNamed:@"blue_btn_normal.png"];
        img=[img stretchableImageWithLeftCapWidth:20 topCapHeight:20];
        [cell.chooseBtn setBackgroundImage:img forState:UIControlStateNormal];
    }
    
    NSDictionary * content = [[message getValue:@"detail"] objectFromJSONString];
    
    NSURL *url= [NSURL URLWithString: [[content objectForKey:@"headImg"] hasPrefix:@"http"]?[content objectForKey:@"headImg"]:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,[content objectForKey:@"headImg"]]];
    [cell.headImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    
    if([message.mesSesion_sess_id isEqualToString:@"cmd_friendValidate"])//好友验证
    {
       
        cell.nameLabel.text = [NSString stringWithFormat:@"%@(%@)",[content objectForKey:@"userName"],[[content objectForKey:@"type"] isEqualToString:@"T"]?@"教职工":@"学生"];
        cell.detailLabel.text =[NSString stringWithFormat:@"%@/%@/%@/%@",[content objectForKey:@"dept"],[content objectForKey:@"profName"],[content objectForKey:@"className"],[content objectForKey:@"sex"]];
        
       // NSString * str =[NSString stringWithFormat:@"%@_%@_friend_%@",DE.userId,[content objectForKey:@"userId" ],DE.userId];
        //20151010
        NSString * str =[NSString stringWithFormat:@"%@_%@_Friend",DE.userId,[content objectForKey:@"userId" ]];
        if ([ContactDao isMyFriend:str]) {
            cell.chooseBtn.titleLabel.text = @"已通过";
            cell.chooseBtn.enabled = NO;
        }else{
            cell.chooseBtn.titleLabel.text = @"通过";
            cell.chooseBtn.enabled = YES;
        }

    }
    else if([message.mesSesion_sess_id isEqualToString:@"cmd_sendJoinGrpRequest"])//邀请好友
    {
        cell.nameLabel.text = [content objectForKey:@"groupName"];
        cell.detailLabel.text = message.text;
    }
    else if([message.mesSesion_sess_id isEqualToString:@"cmd_applyToJoinGrp"])//批准入群
    {
        
        cell.nameLabel.text = [NSString stringWithFormat:@"%@(%@)",[content objectForKey:@"userName"],[[content objectForKey:@"type"] isEqualToString:@"S"]?@"学生":@"教职工"];
        cell.detailLabel.text =[NSString stringWithFormat:@"%@/%@/%@/%@",[content objectForKey:@"dept"],[content objectForKey:@"profName"],[content objectForKey:@"className"],[content objectForKey:@"sex"]];
    }
    cell.message = message;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *message = [msgList objectAtIndex:indexPath.row];
    if([message.mesSesion_sess_id isEqualToString:@"cmd_friendValidate"])//好友验证
    {
        FriendDetailViewController * friendDetail = [[FriendDetailViewController alloc] init];
        friendDetail.friendInfoDic = [[message getValue:@"detail"] objectFromJSONString];
        friendDetail.validationStr = session.text;
        friendDetail.onOperateListener = self;
        friendDetail.message = message;
        friendDetail.friendtype = @"2";
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:friendDetail animated:NO];
    }
    else if ([message.mesSesion_sess_id isEqualToString:@"cmd_sendJoinGrpRequest"]) //入群邀请
    {
        JoinGrpValidateViewController *JoinGrpView = [[JoinGrpValidateViewController alloc] init];
        JoinGrpView.groupInfoDic = [[message getValue:@"detail"] objectFromJSONString];
        JoinGrpView.message = message;
        JoinGrpView.onOperateListener = self;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:JoinGrpView animated:NO];
    }
    else if([message.mesSesion_sess_id isEqualToString:@"cmd_applyToJoinGrp"])//批准入群
    {
        
        FriendDetailViewController * friendDetail = [[FriendDetailViewController alloc] init];
        friendDetail.friendInfoDic = [[message getValue:@"detail"] objectFromJSONString];
        friendDetail.validationStr = session.text;
        friendDetail.onOperateListener = self;
        friendDetail.message = message;
        friendDetail.friendtype = @"3";
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:friendDetail animated:NO];
    }
    
}

//tabview的按钮 详情节目返回时候的 代理实现
-(void)onOperateButtonClick:(Message*)message acceptOrNot:(BOOL)accept{
   if (accept) {
       NSString *sSessionId = message.mesSesion_sess_id;
       NSLog(@"sSessionId:%@",sSessionId);
       if ([sSessionId isEqualToString:@"cmd_friendValidate"])//好友验证
       {
           NSDictionary *map = @{@"friend_id":[[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"userId"]};
           [MBProgressHUD showHUDAddedTo:self.view animated:YES];
           
           [DE serverCall:@"addFriend" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
               
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               if(success && data && [data objectForKey:@"result"])
               {
                   //更新通讯录
                   NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                   NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                   
                   [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                       
                       if(success){
                           @try {
                               [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                               
                               UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加好友成功！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                               [view show];
                               
                           }
                           @catch (NSException *exception) {
                               [self showAlerHUD:@"添加好友失败！"];
                           }
                           
                           [self dealAfterOperateRequest:message accpet:YES];
                       }else{
                           [self showAlerHUD:@"添加好友失败！！"];
                       }
                   }];
                   
               }
               else{
                   //[self showAlerHUD:@"添加好友失败！！"];
                   UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"添加好友失败！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                   [view show];
                   [self dealAfterOperateRequest:message accpet:YES];
               }
           }];

       }
       else if([sSessionId isEqualToString:@"cmd_sendJoinGrpRequest"])//邀请入群
       {
           NSLog(@"邀请入群");
           NSDictionary *map = @{@"groupId":[[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"groupId"],@"inviteUserId":[[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"userId"]};
           [MBProgressHUD showHUDAddedTo:self.view animated:YES];
           NSLog(@"groupID:%@",[map objectForKey:@"groupId"]);
           NSLog(@"userID:%@",[map objectForKey:@"inviteUserId"]);
           
           [DE serverCall:@"acceptJoinGrpRequest" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
               NSLog(@"调用结果：%@",desc);
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               if(success /*&& data && [data objectForKey:@"result"]*/)
               {
                   //更新通讯录
                   NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                   NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                   
                   [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                       
                       if(success){
                           @try {
                               [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                               
                               UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"同意邀请入群成功！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                               [view show];
                               
                           }
                           @catch (NSException *exception) {
                               [self showAlerHUD:@"同意邀请入群失败！"];
                           }
                           
                           [self dealAfterOperateRequest:message accpet:YES];
                       }else{
                           [self showAlerHUD:@"同意邀请入群失败！！"];
                       }
                   }];
                   
               }
               else{
                 if([desc isEqualToString:@"群组不存在！"])
                  {
                      UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该群组已被解散" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                      [view show];
                   }
                   else
                   {
                       UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"同意邀请入群失败！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                       [view show];
                   }
                   [self dealAfterOperateRequest:message accpet:YES];
                  
               }
           }];
       }
       else if([sSessionId isEqualToString:@"cmd_applyToJoinGrp"])//批准入群
       {
           NSLog(@"同意批准入群");
           NSDictionary *map = @{@"groupId":[[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"groupId"],@"memberId":[[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"userId"]};
          [MBProgressHUD showHUDAddedTo:self.view animated:YES];
           NSLog(@"groupID:%@",[map objectForKey:@"groupId"]);
           NSLog(@"memberId:%@",[map objectForKey:@"memberId"]);
           
           [DE serverCall:@"acceptJoinGrp" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
               NSLog(@"调用结果：%@",desc);
               [MBProgressHUD hideHUDForView:self.view animated:YES];
               if(success /*&& data && [data objectForKey:@"result"]*/)
               {
                   //更新通讯录
                   NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                   NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                   
                   [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                       
                       if(success){
                           @try {
                               [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                               
                               UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"批准入群成功！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                               [view show];
                               
                           }
                           @catch (NSException *exception) {
                               [self showAlerHUD:@"批准入群失败！"];
                           }
                           
                           [self dealAfterOperateRequest:message accpet:YES];
                       }else{
                           [self showAlerHUD:@"批准入群失败！！"];
                       }
                   }];
                   
               }
               else{
                   //[self showAlerHUD:@"批准入群失败！！"];
                   UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"批准入群失败！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                   [view show];
                   [self dealAfterOperateRequest:message accpet:YES];
               }
           }];

       }
       
    }else{
        [self dealAfterOperateRequest:message accpet:NO];
    }
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        kAppDelegate.needRefrsh = YES;
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)dealAfterOperateRequest:(Message *)message accpet:(BOOL)accpet{
    
    NSString *session_id = message.mesSesion_sess_id;
    NSLog(@"sessionid:%@",session_id);
    if([session_id isEqualToString:@"cmd_friendValidate"]||[session_id isEqualToString:@"cmd_applyToJoinGrp"])//好友验证
    {
        NSString * userId = [[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"userId"];
        for (Message* msg in msgList) {
            
            NSString * otherUid = [[[msg getValue:@"detail"] objectFromJSONString] objectForKey:@"userId"];
            
            if ([userId isEqualToString:otherUid]) {
                session.badgeNumber--;
                [MessageDao deleteMessageById:msg.mID];
            }
        }
        if(session.badgeNumber>0)
        {
            //20150814 如果是多个好友验证或者同意入群，同意一个后，更新messagesesson的title和text
            NSArray *msglisttemp = [MessageDao queryMessageBySessionId:session_id];
            Message *messagefirst = msglisttemp[0];
            session.text = messagefirst.text;
            session.sessionPic = [[[messagefirst getValue:@"detail"] objectFromJSONString] objectForKey:@"headImg"];
            if([session_id isEqualToString:@"cmd_friendValidate"])
            {
                session.title =[NSString stringWithFormat:@"好友验证：%@",[[[messagefirst getValue:@"detail"] objectFromJSONString] objectForKey:@"userName"]];
            }
            else if([session_id isEqualToString:@"cmd_applyToJoinGrp"])
            {
                 session.title =[NSString stringWithFormat:@"入群申请：%@",[[[messagefirst getValue:@"detail"] objectFromJSONString] objectForKey:@"userName"]];
            }
            
        }
    }else if([session_id isEqualToString:@"cmd_sendJoinGrpRequest"]) //邀请入群
    {
        NSString * groupId = [[[message getValue:@"detail"] objectFromJSONString] objectForKey:@"groupId"];
        for (Message* msg in msgList) {
             NSString * othergroupId = [[[msg getValue:@"detail"] objectFromJSONString] objectForKey:@"groupId"];
            
            if ([groupId isEqualToString:othergroupId]) {
                session.badgeNumber--;
                [MessageDao deleteMessageById:msg.mID];
                }
            
        }
        if(session.badgeNumber>0)
        {
            //20150814 如果是多个邀请入群，同意一个入群邀请后，更新messagesesson的title
            NSArray *msglisttemp = [MessageDao queryMessageBySessionId:session_id];
            Message *messagefirst = msglisttemp[0];
            session.text = messagefirst.text;
        }
    }
   [MessageSessionDao updateMessageSession:session];
    //20150730这个修改为只要做了操作就要发广播消息
    if (session.badgeNumber<=0) {
        [MessageSessionDao deleteMessageSession:session.sess_id];}
     //为了刷新消息列表，消息界面收到PUBLIC_ATTENTION_BROADCAST会刷新，因此发出该广播 addBy lq
    [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
    
    msgList= [MessageDao queryMessageBySessionId:session.sess_id];
    [_friendVerifyTableView reloadData];
}

//返回上一级页面
- (void)btnBack {
    kAppDelegate.needRefrsh = YES;
    [super btnBack];
}

@end
